﻿using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using System;
using UnityEngine.UI;

public class WebImageReader : MonoBehaviour
{
    public static WebImageReader instance;
    Coroutine web_Coroutine;

    private void Awake()
    {
        instance = this;
    }

    public void StopLoadImag()
    {
        if(web_Coroutine!=null)
            StopCoroutine(web_Coroutine);

        web_Coroutine = null;
    }

    public void LoadImages(ImageURLs uRLs, Image[] images,  Action OnLoadEnd)
    {
        web_Coroutine = StartCoroutine(LoadImagsFromWeb(uRLs.levelURLs, images));
    }

    IEnumerator LoadImagsFromWeb(string[] uRLs, Image[] images)
    {
        for(int i=0; i<uRLs.Length; i++)
        {
            if (images[i] == null) break;

            UnityWebRequest wr = new UnityWebRequest(uRLs[i]);
            DownloadHandlerTexture texDl = new DownloadHandlerTexture(true);
            wr.downloadHandler = texDl;
            yield return wr.SendWebRequest();

            if (!(wr.isNetworkError || wr.isHttpError))
            {
                print(texDl.texture.width);
                Texture2D t = texDl.texture;
                images[i].sprite = Sprite.Create(t, new Rect(0, 0, t.width, t.height), Vector2.zero, 1f);
            }
            else
            {
                print("read Failed");
            }
            yield return null;
        }

        web_Coroutine = null;
    }
}
